#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <vector>
#include <set>

using namespace std;

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int> ret;
        for (int c : nums)
        {
            ret.insert(c);
            if (ret.size() > 3) ret.erase(ret.begin());
        }
        return ret.size() == 3 ? *ret.begin() : *ret.rbegin();
    }
};
